﻿using CL.Dapper.Repository;
using CL.Game.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CL.Enum.Common;
using System.Data;
using CL.View.Entity.Game;
using Dapper;
using CL.Tools.Common;

namespace CL.Game.DAL
{
    public class RoomRebateDAL : DataRepositoryBase<RoomRebateEntity>
    {
        public RoomRebateDAL(DbConnectionEnum conenum, IDbConnection Db = null) : base(conenum, Db)
        {
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="Entitys"></param>
        /// <returns></returns>
        public bool InsertEntity(List<RoomRebateEntity> Entitys)
        {
            using (IDbTransaction tran = base.db.BeginTransaction())
            {
                try
                {
                    foreach (var item in Entitys)
                        base.Insert_Long(item, tran);
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return false;
                }
            }
        }
        /// <summary>
        /// 查询可回水对象集
        /// </summary>
        /// <returns></returns>
        public List<cv_RebateList> QueryRebateList()
        {
            StringBuilder Str = new StringBuilder();
            Str.Append(" SELECT tab.UserID ,tab.RoomID ,tab.Counts ,tab.Amount ,rr.Rebates FROM ( ");
            Str.Append(" SELECT u.UserID,r.RoomID,COUNT(s.SchemeID) AS Counts,SUM(s.SchemeMoney) AS Amount FROM dbo.CT_Users AS u ");
            Str.Append(" INNER JOIN dbo.CT_UsersBanks AS ub ON ub.UserID = u.UserID AND ISNULL(u.UserMobile,'')<>'' ");
            Str.AppendFormat(" INNER JOIN dbo.CT_Schemes AS s ON s.InitiateUserID=u.UserID AND CONVERT(DATE,s.CreateTime) = CONVERT(DATE,'{0}') AND s.SchemeStatus=18 ",DateTime.Now.AddDays(-1));
            Str.Append(" INNER JOIN dbo.CT_LotteryRoom AS r ON r.RoomCode = s.RoomCode ");
            Str.Append(" GROUP BY u.UserID,u.UserName,r.RoomName,r.RoomID) tab ");
            Str.Append(" INNER JOIN dbo.CT_RoomRebate AS rr ON rr.RoomID = tab.RoomID AND tab.Amount >= rr.MinAmount AND tab.Amount<=rr.MaxAmount AND tab.Counts >= 10 ");
            return new DataRepositoryBase<cv_RebateList>(DbConnectionEnum.CaileGame).QueryList(Str.ToString()).ToList();
        }
        /// <summary>
        /// 保存会员回水
        /// </summary>
        /// <param name="Entitys"></param>
        /// <returns></returns>
        public bool SaveUserRebate(List<cv_Rebate> Entitys)
        {
            var para = new DynamicParameters();
            para.Add("@RebateTables", XmlHelper.Serializer(Entitys.GetType(), Entitys));
            object aa = base.ExecScalar("CP_Rebate", para);
            return Convert.ToInt64(aa) >= 0;
        }
    }
}
